var express = require('express');
var router = express.Router();
var package = require("../package.json");
var dbHelper = require("../app_modules/mongoHelper.js");
var tool = require("../app_modules/tools.js");
var jwtTool = require("../app_modules/JwtTools.js");
var fs = require('fs');

var multiparty = require('multiparty');
router.post('/upload', function (req, res, next) {
  if(!jwtTool.getTokenObj(req).status)
  return res.send({status:"0",msg:"please login.",metadata:{}});

  var form = new multiparty.Form({ uploadDir: package.filePath});   
  form.parse(req, function (err, fields, files) {
        if(files.inputFile==undefined){
          res.send({status:"0",msg:"upload faild,the files is requried.",metadata:{}});
        }
        else if(!err){
            var MetaData=[];
            var url=package.apiUrl+package.filePath.replace("./public/","");
            
            for(i=0;i<files.inputFile.length;i++){
                var file = files.inputFile[i];                   
                var OriginalFile=file.originalFilename;
                var index=OriginalFile.lastIndexOf(".");
                var fileName = OriginalFile.substring(0, index);
                var fileType = OriginalFile.substring(index + 1, OriginalFile.length); 
                //new file name
              var newFileName=fileName+"_myfile_"+tool.Gettimestamp()+"."+fileType;              
                MetaData.push({"index":i,"fileName":newFileName,"href":url+newFileName});
                saveFile(file,newFileName,fileType,function(){
                  fs.rename(file.path,package.filePath + newFileName);
                });                
              }
            return res.send({status:"1",msg:"upload successfully.",metadata:MetaData});
          }
        else
        {
          return res.send({status:"0",msg:"upload error.",metadata:{}});
        }
      });
});

function saveFile (inputFile,newFileName,fileType,callback){ 
   return callback();
  // filetype=filetype.tolowercase();
  // var dirpath=package.filepath; 
  // //if(package.imgtype.indexof(filetype)>=0){
  // if(true){
      // var images = require("images");
      // var sourceimg = inputfile.path; 
      // var imgsize=package.imgsize;
      // for(g=0;g<imgsize.length;g++){
        // var newpath=dirpath+imgsize[g].tostring()+"px/";
        // if (!fs.existssync(newpath)) {
            // fs.mkdirsync(newpath);k
        // }
        // images(sourceimg).resize(imgsize[g])
        // .save(dirpath + newfilename, {});
      // }          
      // return callback();
  // }
  // else 
  // fs.readfile(inputfile.path, 'utf8', function(err, data){
    // console.log(data);  
    // return callback();
  // });

  // var fs = require("fs");
  // var data = '';
  // var readerstream = fs.createreadstream(inputfile.path);
  // readerstream.setencoding('utf8'); 
  // readerstream.on('data', function(chunk) {
    // data += chunk;
  // });
  // readerstream.on('end',function(){   
    // dbhelper.create("file",{"name":newfilename,"type":filetype,"data":data,"createdata":new date()},function(response){
    // })
    // return callback();
  // });
}

router.post('/deleteFile', function (req, res, next) {
  if(!jwtTool.getTokenObj(req).status)
  return res.send({status:"0",msg:"please login.",metadata:{}});
  
  var filename=tool.getObj(req.body.filename,"");
  if(filename==""){
    return res.send({status:"0",msg:"filename is Required",metadata:{}});
  }
  else{  
     fs.unlinkSync(package.filePath + filename);
     return res.send({status:"1",msg:"the files has deleted",metadata:{}});
  }  
});

module.exports = router;